import { useEffect, useState } from 'react';
import { get, post } from '../services/api';
import CommonTable from '../components/CommonTable';
import { Form, Input, Button, Space, Card, InputNumber, message } from 'antd';

function CourseForm({ onClose, onSuccess }) {
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);

    const handleSubmit = async (values) => {
        setLoading(true);
        try {
            await post('courses', values);
            message.success('课程添加成功');      // ✅ 成功提示
            form.resetFields();                    // ✅ 清空表单
            onClose();                             // ✅ 关闭表单
            onSuccess();                           // ✅ 通知父组件刷新
        } catch (error) {
            console.error('添加课程失败:', error);
            message.error('添加失败，请重试');
        } finally {
            setLoading(false);
        }
    };

    return (
        <Card style={{ marginBottom: 24, boxShadow: '0 1px 2px rgba(0, 0, 0, 0.1)' }}>
            <Form
                form={form}
                layout="vertical"
                onFinish={handleSubmit}
                initialValues={{ course_name: '', credits: '', hours: '' }}
            >
                <Form.Item
                    name="course_name"
                    label={<span style={{ fontSize: '16px' }}>课程名称</span>}
                    rules={[{ required: true, message: '请输入课程名称！' }]}
                >
                    <Input placeholder="请输入课程名称" style={{ fontSize: '16px' }} />
                </Form.Item>

                <Form.Item
                    name="credits"
                    label={<span style={{ fontSize: '16px' }}>学分</span>}
                    rules={[
                        { required: true, message: '请输入学分！' },
                        { type: 'number', min: 1, max: 10, message: '学分必须在1-10之间！' }
                    ]}
                >
                    <InputNumber
                        style={{ width: '100%', fontSize: '16px' }}
                        placeholder="请输入学分"
                        min={1}
                        max={10}
                    />
                </Form.Item>

                <Form.Item
                    name="hours"
                    label={<span style={{ fontSize: '16px' }}>学时</span>}
                    rules={[
                        { required: true, message: '请输入学时！' },
                        { type: 'number', min: 1, max: 200, message: '学时必须在 1-200 之间！' }
                    ]}
                >
                    <InputNumber
                        style={{ width: '100%', fontSize: '16px' }}
                        placeholder="请输入学时"
                        min={1}
                        max={200}
                    />
                </Form.Item>

                <Form.Item>
                    <Space>
                        <Button type="primary" htmlType="submit" loading={loading} style={{ fontSize: '16px' }}>
                            添加课程
                        </Button>
                        <Button onClick={onClose} style={{ fontSize: '16px' }}>取消</Button>
                    </Space>
                </Form.Item>
            </Form>
        </Card>
    );
}

function CoursesPage() {
    const [courses, setCourses] = useState([]);
    const [loading, setLoading] = useState(false);
    const [showForm, setShowForm] = useState(false);

    const fetchCourses = async () => {
        setLoading(true);
        try {
            const data = await get('courses');
            console.log('获取课程数据成功:', data);
            setCourses(data);
        } catch (error) {
            console.error('获取课程数据失败:', error);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchCourses();
    }, []);

    const columns = [
        {
            title: <span style={{ fontSize: '16px' }}>课程编号</span>,
            dataIndex: 'course_id',
            key: 'course_id',
            sorter: (a, b) => a.course_id.localeCompare(b.course_id),
            width: '20%',
        },
        {
            title: <span style={{ fontSize: '16px' }}>课程名称</span>,
            dataIndex: 'course_name',
            key: 'course_name',
            sorter: (a, b) => a.course_name.localeCompare(b.course_name),
            width: '30%',
        },
        {
            title: <span style={{ fontSize: '16px' }}>学分</span>,
            dataIndex: 'credits',
            key: 'credits',
            sorter: (a, b) => a.credits - b.credits,
            width: '15%',
        },
        {
            title: <span style={{ fontSize: '16px' }}>学时</span>,
            dataIndex: 'hours',
            key: 'hours',
            sorter: (a, b) => a.hours - b.hours,
            width: '15%',
        },
    ];

    return (
        <CommonTable
            title="课程管理"
            columns={columns}
            dataSource={courses}
            loading={loading}
            rowKey="course_id"
            searchFields={['course_id', 'course_name']}
            onAdd={() => setShowForm(true)}
            extraContent={
                showForm && (
                    <CourseForm
                        onClose={() => setShowForm(false)}
                        onSuccess={fetchCourses} // ✅ 添加成功后刷新
                    />
                )
            }
        />
    );
}

export default CoursesPage;
